package com.bzsg.rightsManagementSystem.config.security_config

import com.bzsg.rightsManagementSystem.pojo.Permission

import com.bzsg.rightsManagementSystem.service.PermissionService
import com.bzsg.rightsManagementSystem.service.UserService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.stereotype.Component
import kotlin.math.log

@Component
class UserDetailsServiceImpl : UserDetailsService {

    @Autowired
    lateinit var userService: UserService

    @Autowired
    lateinit var permissionService: PermissionService

    @Throws(UsernameNotFoundException::class)
    override fun loadUserByUsername(userName: String): UserDetails {
        //根据用户名查询用户
        val user = userService.selectUserByName(userName)
        val grantedAuthorities = ArrayList<GrantedAuthority>()
        if (user != null) {
            //获取该用户所拥有的权限
            val sysPermissions = permissionService.selectListByUser(user.id)
            // 声明用户授权
            if (sysPermissions?.get(0) != null) {
                sysPermissions.forEach { sysPermission: Permission? ->
                    val grantedAuthority: GrantedAuthority = SimpleGrantedAuthority(sysPermission!!.permissionCode)
                    grantedAuthorities.add(grantedAuthority)
                }
            }
            return User(
                user.userName,
                user.password,
                user.enabled,
                user.accountNonExpired,
                user.credentialsNonExpired,
                user.accountNonLocked,
                grantedAuthorities
            )
        }
        return User(
            userName,
            null,
            grantedAuthorities
        )

    }

}